package com.fraud.bean;

import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.log4j.Logger;

import com.fraud.Util;
import com.fraud.dao.EventLogDao;
import com.fraud.dao.KullaniciDao;
import com.fraud.dao.SubeDao;
import com.fraud.fm.FtpFileManager;
import com.fraud.fm.WindowsFileManager;
import com.fraud.model.entity.Bolge;
import com.fraud.model.entity.EventLog;
import com.fraud.model.entity.Kullanici;
import com.fraud.model.entity.Sube;
import com.fraud.model.type.BaglantiTipi;
import com.fraud.model.type.Durum;
import com.fraud.model.type.EventType;

@Singleton
@Startup
public class FileCollectorBean {

	private final Logger logger = Logger.getLogger(FileCollectorBean.class);

	@PersistenceContext
	EntityManager entityManager;

	@EJB
	SubeDao subeDao;

	@EJB
	EventLogDao jobLogDao;

	@EJB
	KullaniciDao userDao;

	public void collectFiles(Date islemTarihi, Kullanici user) {
		List<Sube> subes = subeDao.getAllSubes();

		for (Sube sube : subes) {

			String date = islemTarihi.getYear() + "-" + islemTarihi.getMonth()
					+ "-" + islemTarihi.getDate();

			logger.debug("Start to collect File," + sube.toString()
					+ " File Process Date:" + date);

			if (user == null) {
				user = userDao.getSystemKullanici();
			}

			collectSubeFile(sube, islemTarihi, user);

			logger.debug("Finished to collect File" + sube.toString()
					+ " File Process Date:" + date);
		}

	}

	public boolean collectSubeFile(Sube sube, Date islemTarihi, Kullanici user) {

		EventLog event = new EventLog();
		event.setBaslangicTarih(new Date());
		event.setKullanici(user);
		event.setSube(sube);
		event.setDosyaTarihi(islemTarihi);
		event.setEventType(EventType.DosyaTransfer);
		String fileName = Util.getDownloadFileName(islemTarihi);
		event.setFileName(fileName);

		boolean isSuccess = true;
		try {
			if (sube.getBaglantiTipi().equals(BaglantiTipi.WINDOWSSHARE)) {
				WindowsFileManager fm = new WindowsFileManager();
				fm.copyFiles(sube, fileName);
				event.setDurum(Durum.BASARILI);

			} else if (sube.getBaglantiTipi().equals(BaglantiTipi.FTP)) {
				FtpFileManager fm = new FtpFileManager();
				fm.copyFiles(sube, fileName);
				event.setDurum(Durum.BASARILI);
			} else {
				logger.error("Invalid connection type ,");
			}

		} catch (Exception e) {
			event.setDurum(Durum.BASARISIZ);
			logger.error("Error while collecting files,Sube:" + sube.getId(), e);
			isSuccess = false;
		} finally {
			event.setBitisTarih(new Date());
			jobLogDao.log(event);
		}
		return isSuccess;

	}

}
